package com.ax.center.service.impl;

import com.ax.center.dto.ApiResponse;
import com.ax.center.dto.StaffDTO;
import com.ax.center.entity.Staff;
import com.ax.center.entity.Users;
import com.ax.center.mapper.StaffDTOMapper;
import com.ax.center.mapper.StaffMapper;
import com.ax.center.mapper.UsersMapper;
import com.ax.center.service.StaffService;
import com.ax.center.service.UserAuthService;
import com.ax.center.service.UserRoleService;
import com.ax.center.service.UsersService;
import com.ax.center.urils.NumberUtils;
import com.ax.center.urils.TimeUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author zy
 * @date 2023/7/4 11:07
 */
@Service
public class StaffServiceImpl extends ServiceImpl<StaffMapper, Staff> implements StaffService {
    @Autowired
    private  StaffMapper staffMapper;

    @Autowired
    private StaffDTOMapper staffDTOMapper;
    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private UserAuthService userAuthService;

    @Override
    public Staff insert() {
        String nowTime= TimeUtils.getStartOfData(new Date());
        LocalDate curTime = LocalDate.now();
        String currentDate = curTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        String validTime=curTime.plusYears(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        String randomNumbers = NumberUtils.generateRandomNumbers(8);
        String staffId = currentDate + randomNumbers;

        // 检查工号的唯一性
        Staff existingStaff = staffMapper.selectOne(new QueryWrapper<Staff>().eq("staff_id", staffId));
        if (existingStaff != null) {
           return null;
        }
        // 创建新的 Staff 对象并插入数据库
        Staff staff = new Staff();
        staff.setId(Long.parseLong(staffId)).setGmtCreate(nowTime).setStatus("有效").setValidity(validTime);
        staffMapper.insert(staff);
        return  staff;
    }

    @Override
    public Staff insert(String status) {
        String nowTime= TimeUtils.getStartOfData(new Date());
        LocalDateTime curTime = LocalDateTime.now();
        String currentDate = curTime.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String validTime=curTime.plusYears(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        String randomNumbers = NumberUtils.generateRandomNumbers(8);
        StringBuilder stringBuilder = new StringBuilder();
        StringBuilder append = stringBuilder.append(currentDate).append(randomNumbers);
        String staffId = append.toString();
        long l = Long.parseLong(staffId);

        // 检查工号的唯一性
        QueryWrapper<Staff> queryWrapper = new QueryWrapper<Staff>();
        queryWrapper.eq("id", l);
        Staff existingStaff = staffMapper.selectOne(queryWrapper);
        if (existingStaff != null) {
         return null;
        }
        // 创建新的 Staff 对象并插入数据库
        Staff staff = new Staff();
        staff.setId(l).setGmtCreate(nowTime).setStatus("有效").setValidity(validTime)
                .setStatus(status);
        System.out.println(staff);
        staffMapper.insert(staff);
        return  staff;
    }


    @Override
    public ApiResponse update(Long id,String newId) { //此位置的修改操作只是修改后8位 前8位为年月日不必修改 所以前端只需要提供后8位

        String oldId=String.valueOf(id);
        String oldpre = oldId.substring(0,8);// 拼接成新的工号
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(oldpre).append(newId);
        long l = Long.parseLong(stringBuilder.toString());
        System.out.println(l);
        // 检查工号的唯一性
        Staff existingStaff = staffMapper.selectOne(new QueryWrapper<Staff>().eq("id", l));
        if (existingStaff != null) {
            return ApiResponse.fail("工号已存在");
        }
        // 更新工号
        update().set("id",l).eq("id",id).update();
        return ApiResponse.ok("工号修改成功");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResponse deleteById(Long id) {
        Long count = query().eq("id", id).count();
        if(count<1){
            return ApiResponse.fail("该工号不存在");
        }
        QueryWrapper<Users> usersQueryWrapper = new QueryWrapper<>();
        usersQueryWrapper.in("staff_id",id);
        Users user = usersMapper.selectOne(usersQueryWrapper);
        Long userId = user.getId();
        removeById(id);
        userRoleService.deleteByUserId(userId);
        userAuthService.deleteByUserId(userId);
        return ApiResponse.ok("删除成功");
    }

    @Override
    public ApiResponse queryAll1() {
        //拿到所有的工号
        List<Staff> staffs = query().list();
        return ApiResponse.ok(staffs);
    }

    @Override
    public ApiResponse queryAll2() {
        //拿到所有的工号
        List<Staff> staffs = query().list();
        List<Staff> filteredStaffs = staffs.stream()
                .filter(staff -> "有效".equals(staff.getStatus()))  // 过滤出状态为 "有效" 的员工
                .collect(Collectors.toList());  // 将过滤后的员工收集到新的列表中

        return ApiResponse.ok(filteredStaffs);
    }

    @Override
    public Staff queryNum(Long id) {
        Staff staff = query().eq("staff_id", id).one();
        return staff;
    }

    @Override
    public ApiResponse updateStatus(Long id,String status) {
        UpdateWrapper<Staff> staffUpdateWrapper = new UpdateWrapper<>();
        staffUpdateWrapper.set("status",status).eq("id",id);
        staffMapper.update(null,staffUpdateWrapper);
        return ApiResponse.ok("更新成功");
    }

    @Override
    public ApiResponse queryStaffWithUser() {
        List<StaffDTO> staffDTOS = staffDTOMapper.queryStaffWithUser();
        return ApiResponse.ok(staffDTOS);
    }
}
